package com.zy.dao.impl;

import com.zy.dao.GetOrderDao;
import com.zy.entity.Order;
import com.zy.entity.User;
import com.zy.service.FindUserByIdService;
import com.zy.service.impl.FindUserByIdServiceImpl;
import com.zy.utils.JdbcUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class GetOrderDaoImpl implements GetOrderDao {

    @Override
    public List<Order> fetchOrders(int userId) {
        List<Order> orders = new ArrayList<>();
        String sql = "SELECT id, payment_amount, payment_time, user_id FROM tb_order WHERE user_id = ?";
        try (Connection connection = JdbcUtil.getConnection();
             PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setInt(1, userId);
            ResultSet rs = stmt.executeQuery();
            FindUserByIdService findUserByIdService = new FindUserByIdServiceImpl();
            while (rs.next()) {
                User user = findUserByIdService.findUserById(rs.getInt("user_id"));
                String username = user != null ? user.getUserName() : "Unknown";
                Order order = new Order(rs.getInt("id"), String.valueOf(rs.getDouble("payment_amount")), new java.util.Date(rs.getTimestamp("payment_time").getTime()), rs.getInt("user_id"), username);
                orders.add(order);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return orders;
    }
}